package love.yuanmengrobot.qdkaoqin.business;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.NetworkOnMainThreadException;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Timer;
import java.util.TimerTask;

import love.yuanmengrobot.qdkaoqin.R;
import love.yuanmengrobot.qdkaoqin.business.MainActivity;
import love.yuanmengrobot.qdkaoqin.entity.Member;
import love.yuanmengrobot.qdkaoqin.util.Constants;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ToLoginActivity extends AppCompatActivity {
    public static final String LOGIN_MESSAGE = "love.yuanmengrobot.chjy.LOGIN_MESSAGE";
    public static final String MEMBER_MESSAGE = "love.yuanmengrobot.chjy.MEMBER_MESSAGE";

    private EditText inaccount;
    private EditText pwd;
    private CheckBox remember;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        Intent intent = getIntent();
        String message = intent.getStringExtra(MainActivity.MESSAGE_STRING);
        TextView textView = findViewById(R.id.identify);
        textView.setText(message);
        String perm;
        if(message.contains("学生登录")){
            perm="1";
        }else{
            perm="0";
        }
        final String permission=perm;
        final EditText usernameEdit=findViewById(R.id.username);
        final EditText passwordEdit=findViewById(R.id.password);

        inaccount=usernameEdit;
        pwd=passwordEdit;
        remember=findViewById(R.id.checkpwd);

        String spFileName = getResources()
                .getString(R.string.shared_preferences_file_name);
        String accountKey = getResources()
                .getString(R.string.login_account_name);
        String passwordKey =  getResources()
                .getString(R.string.login_password);
        String rememberPasswordKey = getResources()
                .getString(R.string.login_remember_password);

        SharedPreferences spFile = getSharedPreferences(
                spFileName,
                MODE_PRIVATE);
        String account = spFile.getString(accountKey, null);
        String password = spFile.getString(passwordKey, null);
        Boolean rememberPassword = spFile.getBoolean(
                rememberPasswordKey,
                false);

        if (account != null && !TextUtils.isEmpty(account)) {
            inaccount.setText(account);
        }

        if (password != null && !TextUtils.isEmpty(password)) {
            pwd.setText(password);
        }

        remember.setChecked(rememberPassword);

        //登录
        Button loginButton = findViewById(R.id.loginbutton);
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                {
                    checkPwdRemember();
                    get(usernameEdit.getText().toString(),passwordEdit.getText().toString(),permission);
                }
            }
        });

        //返回begin
        Button loginBack=findViewById(R.id.login_Back);
        loginBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();//结束当前活动，返回上一个活动
            }
        });
    }

    public void checkPwdRemember(){
        String spFileName = getResources()
                .getString(R.string.shared_preferences_file_name);
        String accountKey = getResources()
                .getString(R.string.login_account_name);
        String passwordKey =  getResources()
                .getString(R.string.login_password);
        String rememberPasswordKey = getResources()
                .getString(R.string.login_remember_password);

        SharedPreferences spFile = getSharedPreferences(
                spFileName,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = spFile.edit();

        if (remember.isChecked()) {
            String password = pwd.getText().toString();
            String account = inaccount.getText().toString();

            editor.putString(accountKey, account);
            editor.putString(passwordKey, password);
            editor.putBoolean(rememberPasswordKey, true);
            editor.apply();
        } else {
            editor.remove(accountKey);
            editor.remove(passwordKey);
            editor.remove(rememberPasswordKey);
            editor.apply();
        }
    }

    private okhttp3.Callback callback = new okhttp3.Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
//            Log.e(TAG, "Failed to connect server!");
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
                final String body = response.body().string();
//                System.out.println(body);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Gson gson = new Gson();
                        Type jsonType =////////****
                                new TypeToken<Member>() {
                                }.getType();
                        Member member = gson.fromJson(body, jsonType);
                        if ("登录成功".equals(member.getMeg())){
                            if("0".equals(member.getPermission())){//跳转到教师首页

                                Intent intent = new Intent(ToLoginActivity.this,
                                        TeacherMainActivity.class);
                                intent.putExtra(ToLoginActivity.MEMBER_MESSAGE, body);
                                startActivity(intent);
                            }else{
                                //跳转到学生首页
                                    Intent intent = new Intent(ToLoginActivity.this,
                                            StudentHomeActivity.class);
                                    intent.putExtra(ToLoginActivity.MEMBER_MESSAGE,
                                            body);
                                    startActivity(intent);
                            }

                        }else if("登录失败".equals(member.getMeg())){
                            final AlertDialog alertDialog1 = new AlertDialog.Builder(ToLoginActivity.this)
                                    .setTitle("警告！")//标题
                                    .setMessage("用户名或密码错误！")//内容
                                    .setIcon(R.mipmap.ic_warning)
                                    .create();
                            alertDialog1.show();
                            final Timer t=new Timer();//设置警告窗口自动关闭
                            t.schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    alertDialog1.dismiss();
                                    t.cancel();
                                }
                            },2000);//2秒后警告窗口自动关闭
                        }
                    }
                });
            } else {
                final AlertDialog alertDialog1 = new AlertDialog.Builder(ToLoginActivity.this)
                        .setTitle("错误！")//标题
                        .setMessage("服务请求错误！")//内容
                        .setIcon(R.mipmap.ic_warning)
                        .create();
                alertDialog1.show();
                final Timer t=new Timer();//设置警告窗口自动关闭
                t.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        alertDialog1.dismiss();
                        t.cancel();
                    }
                },2000);//2秒后警告窗口自动关闭
            }
        }
    };
    public void get(final String username,final String password, final String perm) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String urlParams = "?id="+username+"&paw="+password+"&permission="+perm;//参数
                Request request = new Request.Builder()
                        .url(Constants.LOGIN_URL + urlParams)
                        .get().build();
                try {
                    OkHttpClient client = new OkHttpClient();
                    client.newCall(request).enqueue(callback);
                } catch (NetworkOnMainThreadException ex) {

                    ex.printStackTrace();
                }
            }
        }).start();
    }

}